package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.MessageConstant;
import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Random;

/**
 * @Author: lcc
 * @Desc: 用户管理-业务实现
 * @Date: 2022/6/5 18:59
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Integer sendVerifyCode(String phone) {
        if(StringUtils.isBlank(phone)){
            throw new RuntimeException(MessageConstant.PHONE_IS_NOT_EXIST);
        }
        int verifyCode = new Random().nextInt(9000) + 1000;
        System.out.println("手机号为：【"+phone+"】的验证码是："+verifyCode);
        return verifyCode;
    }

    @Override
    public Long login(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone.trim());
        User user = userMapper.selectOne(wrapper);
        if(user!=null){
            return user.getId();
        }
        user = new User();
        user.setPhone(phone);
        user.setName(phone);
        user.setCreateDate(LocalDate.now());
        user.setAvatar("http://localhost:8080/front/images/user.png");
        userMapper.insert(user);
        return user.getId();
    }
}
